<meta charset='utf8' />
<canvas id='canvas' width='256px' height='256px'></canvas>
<script type="text/javascript" src='../js/vector.js'></script>
<script type="text/javascript" src='../js/ray.js'></script>
<script type="text/javascript" src='../js/substance.js'></script>
<script type="text/javascript" src='../js/perspectiveCamera.js'></script>
<script type="text/javascript" src='../js/color.js'></script>
<script type="text/javascript" src='../js/material.js'></script>
<script type="text/javascript">
	function renderTrace(canvas, scene, camera, maxDepth) {
		var w = canvas.width;
		var h = canvas.height;
		var ctx = canvas.getContext('2d');
		ctx.fillRect(0, 0, w, h);
		var imgData = ctx.getImageData(0, 0, w, h);
		var pixels = imgData.data;

		scene.initialize();
		camera.initialize();

		var i = 0;
		var sx, sy, ray, result, depth;
		for(var y = 0; y < h; y++){
			sy = 1 - y / h;
			for(var x = 0; x < w; x++){
				sx = x / w;
				ray = camera.generateRay(sx, sy);
				result = scene.intersect(ray);
				if(result.geometry){
					//depth = 255 - Math.min((result.distance / maxDepth) * 255, 255);
					var color = result.geometry.material.sample(ray, result.distance, result.normal);
					pixels[i] = color.r * 255;
					pixels[i + 1] = color.g * 255;
					pixels[i + 2] = color.b * 255;
					pixels[i + 3] = 255;
				}
				i += 4;
			}
		}
		ctx.putImageData(imgData, 0, 0);
	}
	var sphere = new Sphere(new Vector3(0, 10, -10), 10);
	sphere.material = new PhoneMaterial(Color.blue, Color.white, 16);
	var camera = new PerspectiveCamera(new Vector3(0, 10, 10), new Vector3(0, 0, -1), new Vector3(1, 0, 0), 90);

	var lightDir = new Vector3(1, 1, 1).normalize();
	var lightColor = Color.white;
	var start = new Date().getTime();
	renderTrace(canvas, sphere, camera, 20);
	var end = new Date().getTime();
	console.log(end - start);
</script>